import os
import requests
import re

"""
- 支持重复消息检查:表示在一定时间间隔内，同样内容（请求json）的消息，不会重复收到
- 调用建议:大部分企业应用在每小时的0分或30分触发推送消息，容易造成资源挤占
- 频率限制:每应用不可超过账号上限数*200人次/天        每应用对同一个成员不可超过30次/分钟，1000次/小时，超过部分会被丢弃不下发
- 如果部分接收人无权限(可见范围和基础接口权限)或不存在，发送仍然执行，但会返回无效的部分
- 接受消息的群体:支持成员、部门、标签
- 内容长度限制:文本消息，markdown不超过2MB
"""




# touser = "yitong.huang" 或 "@all"

class QyWxApp:
    corpid = "ww5719d089888fb0f0"  # 企业id
    agentid = 1000039            # 应用id
    secret = "4Syg5ribEILXINdzFqqoBCRmqvkFVD6Ag8SAdmOcbZM"  # 应用秘钥

    @classmethod
    def get_access_token(cls):
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={cls.corpid}&corpsecret={cls.secret}"
        try:
            res = requests.get(url)
            if res.status_code == 200:
                data = res.json()
                if data.get("errcode") == 0:
                    return data['access_token']
                else:
                    print(f"企业微信返回错误：{data}")
                    return None
            else:
                print(f"HTTP请求失败：状态码 {res.status_code}")
                return None
        except Exception as e:
            print(f"获取access_token失败：{str(e)}")
            return None

    @classmethod
    def media_upload(cls, file_path, media_type="file"):     # 文件上传
        if not os.path.exists(file_path):
            return {"error": "文件不存在"}
        access_token = cls.get_access_token()
        if not access_token:
            return {"error": "access_token获取失败"}
        url = f"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type={media_type}"
        with open(file_path, "rb") as f:
            files = {"media": f}
            res = requests.post(url, files=files)
            return res.json()
    @staticmethod
    def send_file_with_upload(file_path, touser, media_type="file"):      # 文件上传并发送
        res_upload = QyWxApp.media_upload(file_path, media_type)
        if "media_id" in res_upload:
            media_id = res_upload["media_id"]
            return QyWxApp.send_file(touser, media_id)
        else:
            return res_upload

    @classmethod
    def send_msg(cls, touser, content):      # 发送文本内容
        access_token = cls.get_access_token()
        if not access_token:
            return {"error": "access_token获取失败"}
        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
        data = {
            "touser": touser,
            "msgtype": "text",
            "agentid": cls.agentid,
            "text": {"content": content}
        }
        try:
            res = requests.post(url, json=data)
            return res.json()
        except Exception as e:
            return {"error": str(e)}

    @classmethod
    def send_markdown(cls, touser, content):
        access_token = cls.get_access_token()
        if not access_token:
            return {"error": "access_token获取失败"}
        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
        data = {
            "touser": touser,
            "msgtype": "markdown",
            "agentid": cls.agentid,
            "markdown": {"content": content}
        }
        try:
            res = requests.post(url, json=data)
            return res.json()
        except Exception as e:
            return {"error": str(e)}

    @classmethod
    def send_file(cls, touser, media_id):
        access_token = cls.get_access_token()
        if not access_token:
            return {"error": "access_token获取失败"}
        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
        data = {
            "touser": touser,
            "msgtype": "file",
            "agentid": cls.agentid,
            "file": {"media_id": media_id}
        }
        try:
            res = requests.post(url, json=data)
            return res.json()
        except Exception as e:
            return {"error": str(e)}

    @classmethod
    def send_image(cls, touser, media_id):
        access_token = cls.get_access_token()
        if not access_token:
            return {"error": "access_token获取失败"}
        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
        data = {
            "touser": touser,
            "msgtype": "image",
            "agentid": cls.agentid,
            "image": {"media_id": media_id}
        }
        try:
            res = requests.post(url, json=data)
            return res.json()
        except Exception as e:
            return {"error": str(e)}

    @classmethod
    def format_content_to_markdown(cls, content):
        """
        将原始内容转换为符合企业微信规范的Markdown格式
        """
        # 移除所有<font>标签（包括size属性）
        cleaned_content = re.sub(r'<.*?>', '', content)

        # 替换自定义标记为标准标题
        cleaned_content = cleaned_content.replace("[reasoning]###", "###").replace("[/reasoning]", "")
        cleaned_content = cleaned_content.replace("[inference]###", "###").replace("[/inference]", "")

        # 保留代码块的格式，并替换为企业微信规范的code标签
        cleaned_content = re.sub(
            r'```(.*?)```',
            lambda match: '`code`' + match.group(1).replace('\n', '<br/>') + '`code`',
            cleaned_content,
            flags=re.DOTALL
        )
        print(cleaned_content)

        # 替换文件链接为Markdown格式
        cleaned_content = re.sub(
            r'\[file:xls\](http[s]?://\S+)',
            r'[下载文件](\1)',
            cleaned_content
        )

        # 清理多余空行和格式
        return "\n".join([line.strip() for line in cleaned_content.splitlines() if line.strip()])

    @classmethod
    def send_combined_message(cls, touser, raw_content):
        """
        发送整合后的Markdown消息
        """
        formatted_content = cls.format_content_to_markdown(raw_content)
        return cls.send_markdown(touser, formatted_content)
